package com.xuan.yupao.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xuan.yupao.common.ErrorCode;
import com.xuan.yupao.common.Result;
import com.xuan.yupao.constant.PageConstant;
import com.xuan.yupao.constant.UserConstant;
import com.xuan.yupao.exception.BusinessException;
import com.xuan.yupao.model.domain.User;
import com.xuan.yupao.model.domain.request.UserLoginRequest;
import com.xuan.yupao.model.domain.request.UserRegisterRequest;
import com.xuan.yupao.model.domain.request.UserUpdatePasswordRequest;
import com.xuan.yupao.model.domain.vo.UserVo;
import com.xuan.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/user")
//@CrossOrigin (origins = "http://localhost:5173", allowCredentials = "true")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Result<Long> register(@RequestBody UserRegisterRequest userRegisterRequest, HttpServletRequest request) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("[register] userRegisterRequest: {}" ,userRegisterRequest);

        String userAccount = userRegisterRequest.getUserAccount();
        String password = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        long result = userService.userRegister(userAccount, password, checkPassword, request);
        return Result.success(result);
    }

    @PostMapping("/login")
    public Result<Long> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("[login] userLoginRequest: {}" ,userLoginRequest);

        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long userId = userService.userLogin(userAccount, userPassword, request);
        return Result.success(userId);
    }

    @GetMapping("/current")
    public Result<UserVo> getCurrentUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        User user = userService.getById(loginUser.getId());
        UserVo safetyUser = userService.getSafetyUser(user);
        return Result.success(safetyUser);
    }

    @GetMapping("/{userId}")
    public Result<UserVo> getUserVoById(@PathVariable(value = "userId") Long userId, HttpServletRequest request) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数非法");
        }

        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_SESSION);
        UserVo userVo = userService.getUserVoById(userId, loginUser);
        return Result.success(userVo);
    }


    @PostMapping("/logout")
    public Result<Long> logout(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        request.getSession().removeAttribute(UserConstant.USER_SESSION);
        return Result.success(loginUser.getId());
    }


    @GetMapping("/search")
    public Result<List<UserVo>> searchUsers(String username, HttpServletRequest request) {
        log.info("[searchUsers] username: " + username);

        List<UserVo> userList = userService.searchUsers(username, request.getSession());
        return Result.success(userList);
    }

    @PostMapping("/delete")
    public Result<Boolean> deleteUser(Integer id, HttpServletRequest request) {
        if (id == null || id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数非法");
        }
        log.info("[deleteUser] id: " + id);

        boolean result = userService.deleteUser(id, request.getSession());
        return Result.success(result);
    }


    @GetMapping("/search/tags")
    public Result<List<UserVo>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList, Integer pageNum,
                                                  HttpServletRequest request) {
        log.info("[searchUsersByTags] tagNameList: " + tagNameList);
        if (tagNameList == null || pageNum == null || pageNum < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_SESSION);
        List<UserVo> userList = userService.searchUsersByTagNameList(tagNameList, pageNum, loginUser);
        return Result.success(userList);
    }

    @PostMapping("/update")
    public Result<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("[updateUser] user: " + user);

        User loginUser = userService.getLoginUser(request);
        user.setId(loginUser.getId());
        Integer result = userService.updateUser(user, loginUser);
        return Result.success(result);
    }


    @GetMapping("/recommend")
    public Result<List<UserVo>> recommendUsers(Integer pageNum, String username, HttpServletRequest request) {
        if (pageNum == null || pageNum < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("[recommendUsers] pageNum=" + pageNum + ", username=" + username);

        // 未登录用户也可访问该页面
        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_SESSION);
        List<UserVo> recommendUserList = userService.recommendUsers(pageNum, username, loginUser);
        return Result.success(recommendUserList);
    }


    @GetMapping("/match")
    public Result<List<UserVo>> matchUsers(Integer pageNum, String username, HttpServletRequest request) {
        if (pageNum == null || pageNum <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("[matchUsers] pageNum=" + pageNum);

        User loginUser = userService.getLoginUser(request);
        List<UserVo> userVoList = userService.matchUserByQuickSort(pageNum, username, loginUser);
        return Result.success(userVoList);
    }


    @GetMapping("/tags")
    public Result<List<String>> getUserTags(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        Gson gson = new Gson();
        // 此处要从数据库中查询,因为存储在 session 中的用户标签可能已经过时了
        User user = userService.getById(loginUser.getId());
        String tags = user.getTags();
        if (StringUtils.isBlank(tags)) {
            return Result.success(new ArrayList<>());
        }
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        return Result.success(tagList);
    }

    @PostMapping("/update/tags")
    public Result<Boolean> updateUserTags(@RequestBody List<String> tags, HttpServletRequest request) {
        if (tags == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("[updateUserTags] tags:{}", tags);

        User loginUser = userService.getLoginUser(request);
        Gson gson = new Gson();
        String tagsJson = gson.toJson(tags);
        User user = new User();
        user.setId(loginUser.getId());
        user.setTags(tagsJson);
        return Result.success(userService.updateById(user));
    }


    @PostMapping("/update/password")
    public Result<Boolean> updatePassword(@RequestBody UserUpdatePasswordRequest updatePasswordRequest, HttpServletRequest request) {
        if (updatePasswordRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        User loginUser = userService.getLoginUser(request);
        boolean b = userService.updatePassword(updatePasswordRequest, loginUser);
        return Result.success(b);
    }
}
